import React, { useRef, useState, useEffect } from 'react';
import Swiper from 'swiper';
import styles from './SwiperBox.less';
import { isEmpty } from '@/utils/common';

type ISwiperBox = {
  ikey: string;
  data: Array<any>;
  renderRow: Function;
  options?: {};
  wrapClass?: string;
  itemClass?: string;
  dotsClass?: string;
};

const SwiperBox: React.FC<ISwiperBox> = props => {
  const mySwiper = useRef<object>();
  const mySwiperWrap = useRef<HTMLDivElement>(null);
  const [activeIndex, setActiveIndex] = useState(0);

  const initSwiper = () => {
    mySwiper.current = new Swiper(mySwiperWrap.current as HTMLDivElement, {
      // passiveListeners: false,
      on: {
        slideChange: event => {
          // console.log(event.activeIndex)
          setActiveIndex(event.activeIndex);
        },
      },
      ...props.options,
    });
  };

  useEffect(() => {
    if (!isEmpty(props.data)) {
      initSwiper();
    }
  }, [props.data]);

  return (
    <div ref={mySwiperWrap} className={`swiper-container ${props.wrapClass}`}>
      <div className="swiper-wrapper">
        {props.data &&
          props.data.map((item, index) => (
            <div
              key={item[props.ikey || 'id']}
              className={`swiper-slide ${props.itemClass}`}
            >
              {props.renderRow(item, index)}
            </div>
          ))}
      </div>
      {props.data && props.data.length > 1 && (
        <div className={`${styles.swiper_dots} ${props.dotsClass}`}>
          {props.data.map((_, index) => (
            <i
              key={index}
              className={activeIndex === index ? 'active' : ''}
            ></i>
          ))}
        </div>
      )}
    </div>
  );
};

export default SwiperBox;
